var socket = null;
var idCon=-1;
var idApre;
var senhaHash='';
var cor='';
var botaopress=0;
var x1=-1;
var y1=-1;
var x2=-1;
var y2=-1;
var xMouseColo=new Array();//posicao x em que esta o mouse das outras pessoas
var yMouseColo=new Array();//posicao y em que esta o mouse das outras pessoas
var xcursor=new Array();
var ycursor=new Array();
var nConexoes=-1;
function initSocket() { 
    
    var conexaoRealizadaComSucesso=0;//ve se a conexao foi realizada com sucesso
    var host=$('meta[name=slideServer]').attr('host');
    idApre=$('meta[name=slideServer]').attr('id');
    var senha=$('meta[name=senhaDeControle]').attr('senha');
    cor=$('meta[name=corMouse]').attr('val');
    senhaHash=SHA256(senha);
    socket = io.connect(host);
    socket.on('status', function (data) {
    
         socket.on('slideEscravo', function (data) {            
            
            if(lozaAtivada==1){        
                $("#loza"+pageNumRemoto, window.parent.canvasFrame.document).css("z-index", 10);
                $("#loza"+pageNumRemoto, window.parent.canvasFrame.document).css("visibility", "hidden");
            }        
            pageNum=data.slide;
            pageNumRemoto=data.slide;
            $("#nPagina").html(""+data.slide);
            if(lozaAtivada==1){        
                $("#loza"+pageNumRemoto, window.parent.canvasFrame.document).css("z-index", 50);
                $("#loza"+pageNumRemoto, window.parent.canvasFrame.document).css("visibility", "visible");
            }        
            renderPage(data.slide);
        });   
        socket.on('mandarPontoMouseEscravo', function (data) {  
			if(data.idCon!=idCon){
				if(xMouseColo[data.idCon]==undefined && yMouseColo[data.idCon]==undefined ){
					xMouseColo[data.idCon]=data.x;
					yMouseColo[data.idCon]=data.y;
				}
				else if(xMouseColo[data.idCon]==-1 && yMouseColo[data.idCon]==-1){
					xMouseColo[data.idCon]=data.x;
					yMouseColo[data.idCon]=data.y;                
				}
				else{
					if(xMouseColo[data.idCon] !=data.x || yMouseColo[data.idCon]!=data.y){
						desenharMouse(xMouseColo[data.idCon],yMouseColo[data.idCon],data.x,data.y,pageNum);
						xMouseColo[data.idCon]=data.x;
						yMouseColo[data.idCon]=data.y;
					}
				}
			}
        });  
        socket.on('resetarPontoEscravo', function (data) {     
            xMouseColo[data.idCon]=-1;
            yMouseColo[data.idCon]=-1;
        });    
        socket.on('controlLozaEscravo', function (data) {     
            if(data.status=='ativar'){
                $("#loza"+pageNum, window.parent.canvasFrame.document).css("z-index", 50);
                $("#loza"+pageNum, window.parent.canvasFrame.document).css("visibility", "visible");
                lozaAtivada=1;
                $("#AtivarLozaText").html("Desativar <br/> Loza");                
				$("#modoBorracha").addClass("button");
				$("#modoBorracha").removeClass("buttonDisable");
            }
            else{
                $("#loza"+pageNum, window.parent.canvasFrame.document).css("z-index", 10);
                $("#loza"+pageNum, window.parent.canvasFrame.document).css("visibility", "hidden");
                $("#AtivarLozaText").html("Ativar <br/> Loza");
                
				$("#modoBorracha").addClass("buttonDisable");
				$("#modoBorracha").removeClass("button");
                lozaAtivada=0;
            }
            
            
        });               
        socket.on('limparLozaEscravo', function (data) {     
            var elem = document.getElementById('loza');
            var ctx = elem.getContext('2d');                
            ctx.clearRect(0, 0, elem.width, elem.height);  
        });   
        socket.on('mandarPontoCursorMouseEscravo', function (data) {
            if(data.idCon!=idCon){
                var elem = window.parent.canvasFrame.document.getElementById('cursor'+data.idCon);
                var ctx = elem.getContext('2d');          
                ctx.fillStyle = data.cor;   
                if(xcursor[data.idCon]==undefined && ycursor[data.idCon]==undefined){
					xcursor[data.idCon]=-1;
					ycursor[data.idCon]=-1;
				}
				if(xcursor[data.idCon]!=-1 && ycursor[data.idCon]!=-1){
					ctx.clearRect(xcursor[data.idCon]-10,ycursor[data.idCon]-10, 20,20 );  
				}
				ctx.fillRect(data.x-5,data.y-5, 10,10 );
				        
			}
			
			xcursor[data.idCon]=data.x;
			ycursor[data.idCon]=data.y;
        });
        
    });    
    socket.emit('iniConexaoMaster', { idApresentcao: idApre, senha: senhaHash});
    socket.on('sucessoConexao', function (data) {
        idCon=data.idCon;
        
        for(var i=0; i<data.nConexoes;i++){
            $('#divDocPdf', window.parent.canvasFrame.document).append("<canvas id=\"cursor"+i+"\" style=\"position: absolute; top:0; left:0px; z-index:90;  width:"+canvas.width+"px; height:"+canvas.height+"px\" width=\""+canvas.width+"\" height=\""+canvas.height+"\" ></canvas>");
        }
        nConexoes=data.nConexoes;
    });
    socket.on('falhaConexao', function (data) {       
        alert('Já existe uma apresentação com o id '+idApresentacao +' no slideServer '+host+', você não tem a senha correta para manipulá-la');    
    });
    socket.on('novaConexao',  function (data) {       
        if(idCon!=data.idCon){
            $('#divDocPdf', window.parent.canvasFrame.document).append("<canvas id=\"cursor"+data.idCon+"\" style=\"position: absolute; top:0; left:0px; z-index:90;  width:"+canvas.width+"px; height:"+canvas.height+"px\" width=\""+canvas.width+"\" height=\""+canvas.height+"\" ></canvas>");
            if(nConexoes!=-1){
                nConexoes=nConexoes+1;
            }
        }
    });
    socket.on('alguemDisconectou', function(data){
    $('#cursor'+data.idCon, window.parent.canvasFrame.document).remove();
    
    });
    //ve se a conexao foi realizada com sucesso
    window.setTimeout(function() {
        if(conexaoRealizadaComSucesso==0){
            alert('Não é possivel se conectar no slideServer '+host);
        }
    }, 15000);
    socket.on('connect', function (data){
        conexaoRealizadaComSucesso=1;
    });
    //fim
    socket.on('mandarModoBorrachaEscravo', function (data){
    modoBorracha=data.modo;
    if(data.modo==1){
        $("#modoBorrachaText").html(" Modo <br/> Pincel");   
		
    }
    else{
        $("#modoBorrachaText").html(" Modo <br/> Borracha");    		
    }
    });
}


//sincroniza o slide mestre com o escravo
function mandarSlideAtual(page){
    if(socket==null || idCon==-1) return;
    socket.emit('slideMestre', { idApresentcao: idApre , slide: page, senha: senhaHash, idCon:idCon});                            
} 
//fim
//manda ponto para ser desenhado no canvas do escravo
function mandarPontoXY(x,y){
    if(socket==null || idCon==-1) return;
	if(xMouseColo[idCon]==undefined && yMouseColo[idCon]==undefined ){
		xMouseColo[idCon]=x;
		yMouseColo[idCon]=y;
	}
	else if(xMouseColo[idCon]==-1 && yMouseColo[idCon]==-1){
		xMouseColo[idCon]=x;
		yMouseColo[idCon]=y;                
	}
	else{
		if(xMouseColo[idCon] !=x || yMouseColo[idCon]!=y){
			desenharMouse(xMouseColo[idCon],yMouseColo[idCon],x,y,pageNum);
			xMouseColo[idCon]=x;
			yMouseColo[idCon]=y;
		}
	}
    socket.emit('mandarPontoMouseMestre', { idApresentcao: idApre , x: x , y: y, senha: senhaHash, idCon:idCon});
}
function mandarPontoXYCursorMouse(x,y){
    if(socket==null || idCon==-1) return;
	if(lozaAtivada==1 && modoBorracha==1){//desenha uma borracha no computador que a ativou
		var elem = window.parent.canvasFrame.document.getElementById('cursor'+idCon);
		var ctx = elem.getContext('2d');          
		if(x2!=-1 && y2!=-1){
			ctx.clearRect(x2-15,y2-15, 30,30 );  					
		}				
		ctx.strokeStyle   = '#000000';
		ctx.strokeRect(x-10,y-10,20,20);
		x2=x;
		y2=y;
				
	}
    socket.emit('mandarPontoCursorMouseMestre', { idApresentcao: idApre , x: x , y: y, senha: senhaHash, cor: cor, idCon:idCon});
	
}
function resetarPonto(){
    if(socket==null || idCon==-1) return;
    socket.emit('resetarPontoMestre', { idApresentcao: idApre , status:'resetar', senha: senhaHash, idCon:idCon});
}           
//fim

//habilita e desabilita a loza no escravo
function habilitarLoza(){
    if(socket==null || idCon==-1) return;
    lozaAtivada=1;
    socket.emit('controlLozaMestre', { idApresentcao: idApre , status: 'ativar', senha: senhaHash, idCon:idCon});  
}
function desabilitarLoza(){
    if(socket==null || idCon==-1) return;
    lozaAtivada=0;
	var elem = window.parent.canvasFrame.document.getElementById('cursor'+idCon);
	var ctx = elem.getContext('2d');                
	ctx.clearRect(0, 0, elem.width, elem.height);			
    socket.emit('controlLozaMestre', {idApresentcao: idApre , status: 'desativar', senha: senhaHash, idCon:idCon});   
}
//fim

//limparLoza
function mandarLimparLoza(){
    if(socket==null || idCon==-1) return;
    socket.emit('limparLozaMestre', {idApresentcao: idApre,  senha: senhaHash, idCon:idCon});  
}
//fim

//passa slide, quando as imagens svg correspondentes  sao clicadas
$(document).ready( function(){
    $("#proximaPagina").click(function(){           
        if (pageNum <= pdfDoc.numPages) mandarSlideAtual(pageNum+1);
  //      goNext();
                      
    });
    $("#paginaAnterior").click(function(){
        if (pageNum >1) mandarSlideAtual(pageNum-1);
//        goPrevious();
    });

});
//fim
//habilita e desabilita a loza
var lozaAtivada=0;                        
function initAtivarLoza(){
    $("#AtivarLoza").click(function(){//quanto shift+z é pressionado habilita ou desabilita a loza                    
        if(lozaAtivada==0){                                              
          //  $("#loza").css("z-index", 60);
           // $("#loza").css("visibility", "visible");
            lozaAtivada=1;
            habilitarLoza();
        }
        else{                                            
           // $("#loza").css("z-index", 10);
           // $("#loza").css("visibility", "hidden");
            lozaAtivada=0;
            desabilitarLoza();
        }
    }); 
    $("#modoBorracha").click(function (){
		if(lozaAtivada==1){
			if(modoBorracha==1){
				modoBorracha=0;        
				var elem = window.parent.canvasFrame.document.getElementById('cursor'+idCon);
				var ctx = elem.getContext('2d');                
				ctx.clearRect(0, 0, elem.width, elem.height);				
			}
			else{
				modoBorracha=1;        
			}
			socket.emit('mandarModoBorrachaMestre', {idApresentcao: idApre , modo: modoBorracha, senha: senhaHash, idCon:idCon});  
		}
    });
}
 
//fim
//limpa a loza
$(document).keypress(function(e){
    if(e.charCode == 88 ){//quanto shift+x é pressionado habilita ou desabilita a loza                    
        limparLoza();
        mandarLimparLoza();
    }
}); 
//desenha loza

function initLoza() { 
    $("#divDocPdf", window.parent.canvasFrame.document).bind('mouseup',function(e){
        if(botaopress==1){ 
            botaopress=0;
            x1=-1;
            y1=-1;
            resetarPonto();
        }
    }).bind('mousedown',function(e){
        if(e.button==0 && botaopress==0){
            botaopress=1;
        }
    }).bind('mousemove',function(e){ 
        if(botaopress==1 &&  lozaAtivada==1){
            adjx=canvasLoza.attr("width")/canvas.width;
            adjy=canvasLoza.attr("height")/canvas.height;
            if(x1==-1 && y1==-1){
                x1=parseInt(e.pageX*adjx);
                y1=parseInt(e.pageY*adjy);
            }
            else{                
                if(x1!=parseInt(e.pageX*adjx) || y1!=parseInt(e.pageY*adjy)){
                    //desenharMouse(x1,y1,parseInt(e.pageX*adjx),parseInt(e.pageY*adjy));                
                    x1=parseInt(e.pageX*adjx);
                    y1=parseInt(e.pageY*adjy);
                }
            }
            mandarPontoXY(parseInt(e.pageX*adjx),parseInt(e.pageY*adjy));
        }
    }).bind('mouseout',function(e){ 
        botaopress=0;
    });
}
//fim

//desenha o cursor do mouse no escravo
function initCursor(){ 
    $("#divDocPdf", window.parent.canvasFrame.document).bind('mousemove',function(e){     
        adjx=canvasLoza.attr("width")/canvas.width;
        adjy=canvasLoza.attr("height")/canvas.height;
        mandarPontoXYCursorMouse(parseInt(e.pageX*adjx),parseInt(e.pageY*adjy));
    });
}
//fim
//zomm in e zomm out na apresentacao
function initZoom(){
    $("#zoomIn").click(function(){           
        for(var i=0; i<pdfDoc.numPages;i++){
            var lozaTemp=$("#loza"+(i+1), window.parent.canvasFrame.document);
            lozaTemp.css("width", parseInt(canvas.width*1.05)+"px"); 
            lozaTemp.css("height",parseInt(canvas.height*1.05)+"px");
        }
        for(var i=0; i<nConexoes;i++){
            var cursorTemp=$("#cursor"+i, window.parent.canvasFrame.document);
            cursorTemp.css("width", parseInt(canvas.width*1.05)+"px"); 
            cursorTemp.css("height",parseInt(canvas.height*1.05)+"px");
        }
        $("#the-canvas", window.parent.canvasFrame.document).css("width", parseInt(canvas.width*1.05)+"px"); 
        $("#the-canvas", window.parent.canvasFrame.document).css("height",parseInt(canvas.height*1.05)+"px");
        //$("#divDocPdf", window.parent.canvasFrame.document).css("width", parseInt(canvas.width*0.95)+"px"); 
        //$("#divDocPdf", window.parent.canvasFrame.document).css("height",parseInt(canvas.height*0.95)+"px");
       
        canvasLoza.css("width", parseInt(canvas.width*1.05)+"px"); 
        canvasLoza.css("height",parseInt(canvas.height*1.05)+"px");


        canvas.height = parseInt(canvas.height*1.05);        
        canvas.width = parseInt(canvas.width*1.05);         

        ajustarFrameCanvas();
        renderPage(pageNum);
    });
    $("#zoomOut").click(function(){
        for(var i=0; i<pdfDoc.numPages;i++){
            var lozaTemp=$("#loza"+(i+1), window.parent.canvasFrame.document);
            lozaTemp.css("width", parseInt(canvas.width*0.95)+"px"); 
            lozaTemp.css("height",parseInt(canvas.height*0.95)+"px");
        }
        for(var i=0; i<nConexoes;i++){
            var cursorTemp=$("#cursor"+i, window.parent.canvasFrame.document);
            cursorTemp.css("width", parseInt(canvas.width*0.95)+"px"); 
            cursorTemp.css("height",parseInt(canvas.height*0.95)+"px");
        }
        canvasLoza.css("width", parseInt(canvas.width*0.95)+"px"); 
        canvasLoza.css("height",parseInt(canvas.height*0.95)+"px");
       
        $("#the-canvas",window.parent.canvasFrame.document).css("width", parseInt(canvas.width*0.95)+"px"); 
        $("#the-canvas",window.parent.canvasFrame.document).css("height",parseInt(canvas.height*0.95)+"px");
        //$("#divDocPdf",window.parent.canvasFrame.document).css("width", parseInt(canvas.width*0.95)+"px"); 
        //$("#divDocPdf",window.parent.canvasFrame.document).css("height",parseInt(canvas.height*0.95)+"px");

        canvas.height = parseInt(canvas.height*0.95);        
        canvas.width = parseInt(canvas.width*0.95);      
        ajustarFrameCanvas();
        renderPage(pageNum);

    });

}
//fim
//pegar valores get da url no javascript, peguei esta dica no blog http://gustavopaes.net/blog/2009/javascript-pegar-valor-de-um-parametro-na-url.html
function _GET(name)
{
  var url   = window.location.search.replace("?", "");
  var itens = url.split("&");

  for(n in itens)
  {
    if( itens[n].match(name) )
    {
      return decodeURIComponent(itens[n].replace(name+"=", ""));
    }
  }
  return null;
}
window.onload = function() {
        //muda configuracoes da tag meta
        var corM=_GET("corMouse");
        $('meta[name=corMouse]').attr('val',corM);        
        //fim
        //carrega os componentes do iframe
        var iframe=$("#canvasFrame");
        $(iframe).ready(function (){
            initLoza();
            initCursor();
            initZoom();
            initAtivarLoza();
            arqPDF=$('meta[name=slideFile]').attr('src');
            canvas = window.parent.canvasFrame.document.getElementById('the-canvas');
            canvasLoza = $("#loza", window.parent.canvasFrame.document);
            ctx=canvas.getContext('2d');           
            openPDF(arqPDF);
            ajustarFrameCanvas();
            initSocket();

        });
        //fim

}

